using System;
using System.Collections.Generic;
using System.Drawing;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
using CCWin;
using CCWin.SkinControl;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ERP_SaaS_WinForm.物料管理
{
    public class PinkingDetailForm : CCSkinMain
    {
        private readonly string _pickFormCode;

        private TextBox txtCode;
        private TextBox txtName;
        private TextBox txtDate;
        private TextBox txtPicker;
        private TextBox txtProductionOrder;
        private TextBox txtDispatch;
        private SkinDataGridView dgvPicks;

        public PinkingDetailForm(string pickFormCode)
        {
            _pickFormCode = pickFormCode ?? string.Empty;
            InitializeUi();
            this.Load += PinkingDetailForm_Load;
        }

        private void InitializeUi()
        {
            this.Text = "领料单详情";
            this.Size = new Size(900, 600);

            var lblCode = new Label { Text = "领料单编号", Location = new Point(30, 30), AutoSize = true };
            txtCode = new TextBox { Location = new Point(130, 25), Width = 220, ReadOnly = true };

            var lblName = new Label { Text = "领料单名称", Location = new Point(380, 30), AutoSize = true };
            txtName = new TextBox { Location = new Point(480, 25), Width = 220, ReadOnly = true };

            var lblDate = new Label { Text = "领料日期", Location = new Point(30, 70), AutoSize = true };
            txtDate = new TextBox { Location = new Point(130, 65), Width = 220, ReadOnly = true };

            var lblPicker = new Label { Text = "领料人", Location = new Point(380, 70), AutoSize = true };
            txtPicker = new TextBox { Location = new Point(480, 65), Width = 220, ReadOnly = true };

            var lblProd = new Label { Text = "工单编号", Location = new Point(30, 110), AutoSize = true };
            txtProductionOrder = new TextBox { Location = new Point(130, 105), Width = 220, ReadOnly = true };

            var lblDispatch = new Label { Text = "任务编号", Location = new Point(380, 110), AutoSize = true };
            txtDispatch = new TextBox { Location = new Point(480, 105), Width = 220, ReadOnly = true };

            dgvPicks = new SkinDataGridView
            {
                Location = new Point(30, 160),
                Size = new Size(820, 360),
                ReadOnly = true,
                AllowUserToAddRows = false,
                AllowUserToDeleteRows = false,
                AutoGenerateColumns = false,
                SelectionMode = DataGridViewSelectionMode.FullRowSelect
            };

            dgvPicks.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "物料编号", DataPropertyName = "materialCode", Width = 160 });
            dgvPicks.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "数量", DataPropertyName = "pickingQuantity", Width = 100 });
            dgvPicks.Columns.Add(new DataGridViewTextBoxColumn { HeaderText = "仓库编号", DataPropertyName = "warehouseCode", Width = 160 });

            // Skin 样式细节（可按需调整）
            dgvPicks.EnableHeadersVisualStyles = false;
            dgvPicks.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(235, 243, 255);
            dgvPicks.ColumnHeadersDefaultCellStyle.ForeColor = Color.FromArgb(48, 48, 48);
            dgvPicks.ColumnHeadersHeight = 28;
            dgvPicks.RowHeadersVisible = false;
            dgvPicks.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(245, 249, 255);

            this.Controls.Add(lblCode);
            this.Controls.Add(txtCode);
            this.Controls.Add(lblName);
            this.Controls.Add(txtName);
            this.Controls.Add(lblDate);
            this.Controls.Add(txtDate);
            this.Controls.Add(lblPicker);
            this.Controls.Add(txtPicker);
            this.Controls.Add(lblProd);
            this.Controls.Add(txtProductionOrder);
            this.Controls.Add(lblDispatch);
            this.Controls.Add(txtDispatch);
            this.Controls.Add(dgvPicks);
        }

        private async void PinkingDetailForm_Load(object sender, EventArgs e)
        {
            await LoadDetailsAsync();
        }

        private async Task LoadDetailsAsync()
        {
            if (string.IsNullOrWhiteSpace(_pickFormCode))
            {
                MessageBox.Show("未提供有效的领料单编号");
                return;
            }

            var urls = new List<string>
            {
                $"http://10.223.8.23:8008/api/Pinking/GetCodePinkingOrder?PickFormCode={Uri.EscapeDataString(_pickFormCode)}"
            };

            using (HttpClient client = new HttpClient())
            {
                try
                {
                    HttpResponseMessage resp = null;
                    string json = null;
                    foreach (var u in urls)
                    {
                        try
                        {
                            resp = await client.GetAsync(u);
                            if (resp.IsSuccessStatusCode)
                            {
                                json = await resp.Content.ReadAsStringAsync();
                                break;
                            }
                        }
                        catch
                        {
                        }
                    }

                    if (string.IsNullOrEmpty(json))
                    {
                        MessageBox.Show("获取详情失败");
                        return;
                    }

                    // 兼容：data 可能是对象、数组，或者根就是对象/数组
                    var token = JsonConvert.DeserializeObject<JToken>(json);
                    PickFormDetailData d = null;

                    if (token is JObject obj)
                    {
                        var dataToken = obj["data"] ?? obj; // 如果没有 data，直接用根对象
                        if (dataToken is JArray arr1 && arr1.Count > 0)
                        {
                            d = arr1[0].ToObject<PickFormDetailData>();
                        }
                        else if (dataToken is JObject dobj1)
                        {
                            d = dobj1.ToObject<PickFormDetailData>();
                        }
                    }
                    else if (token is JArray arr && arr.Count > 0)
                    {
                        d = arr[0].ToObject<PickFormDetailData>();
                    }

                    if (d == null)
                    {
                        MessageBox.Show("未获取到详情数据");
                        return;
                    }

                    txtCode.Text = d.pickFormCode;
                    txtName.Text = d.pickFormName;
                    txtDate.Text = d.pickDate.ToString("yyyy-MM-dd HH:mm:ss");
                    txtPicker.Text = d.picker;
                    txtProductionOrder.Text = d.productionOrdersCode;
                    txtDispatch.Text = d.dispatchCode;

                    dgvPicks.DataSource = d.picks ?? new List<PickDetailItem>();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"获取详情异常: {ex.Message}");
                }
            }
        }

        private class PickFormDetailData
        {
            public string pickFormName { get; set; }
            public string pickFormCode { get; set; }
            public DateTime pickDate { get; set; }
            public string picker { get; set; }
            public string productionOrdersCode { get; set; }
            public string dispatchCode { get; set; }
            public int pickInfo { get; set; }
            public List<PickDetailItem> picks { get; set; }
        }

        private class PickDetailItem
        {
            public int pickingId { get; set; }
            public string pickFormCode { get; set; }
            public string materialCode { get; set; }
            public int pickingQuantity { get; set; }
            public string warehouseCode { get; set; }
            public bool isDel { get; set; }
        }
    }
}



